package dhu.cst.jnlwt.jiangnan181310209liwanting181310302.tally.activity_login;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.mob.MobSDK;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import dhu.cst.jnlwt.jiangnan181310209liwanting181310302.tally.R;
import dhu.cst.jnlwt.jiangnan181310209liwanting181310302.tally.activity_tally.HomeActivity;
import dhu.cst.jnlwt.jiangnan181310209liwanting181310302.tally.database.DatabaseHelper;

public class VerificationLoginActivity extends AppCompatActivity implements View.OnClickListener {

    private TextView toPasswordLogin;

    private EditText editText_phone;
    private EditText editText_verification;

    private Button button_sendVerificationBtn;
    private Button button_verify;

    private String phoneNumber;
    private String verificationCode;

    private DatabaseHelper databaseHelper;
    private SQLiteDatabase sqLiteDatabase;

    private EventHandler eh;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg){
            super.handleMessage(msg);
            int result = msg.arg2;
            int event = msg.arg1;
            Object data = msg.obj;
            if (result == SMSSDK.RESULT_COMPLETE) {
                if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                    Toast.makeText(VerificationLoginActivity.this, "验证成功", Toast.LENGTH_SHORT).show();//提交验证码成功
                    if(isRegistered(phoneNumber)){
                        Intent intent = new Intent(VerificationLoginActivity.this, HomeActivity.class);//已注册用户登录成功前往主界面
                        intent.putExtra("phone_toHA",phoneNumber);
                        startActivity(intent);
                    }
                    else{
                        Intent intent = new Intent(VerificationLoginActivity.this, RegisterActivity.class);//未注册用户注册成功前往填写信息界面
                        intent.putExtra("phone_toRA",phoneNumber);
                        startActivity(intent);
                    }
                }
                else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                    Toast.makeText(VerificationLoginActivity.this, "获取验证码成功", Toast.LENGTH_SHORT).show();//获取验证码成功
                }
                else if (event == SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES) { /*返回支持发送验证码的国家列表*/ }
            }
            else {
                Toast.makeText(VerificationLoginActivity.this, "验证码错误", Toast.LENGTH_SHORT).show();
                ((Throwable) data).printStackTrace();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_verification_login);

        //初始化控件
        toPasswordLogin = findViewById(R.id.toPasswordLogin);
        editText_phone = findViewById(R.id.editText_phone);
        editText_verification = findViewById(R.id.editText_verification);
        button_sendVerificationBtn = findViewById(R.id.button_sendVerification);
        button_verify = findViewById(R.id.button_verify);
        toPasswordLogin = findViewById(R.id.toPasswordLogin);
        TextView title = findViewById(R.id.appName_verification);
        Typeface typeface = Typeface.createFromAsset(getAssets(),"myFont.ttf");
        title.setTypeface(typeface);
        //按钮点击事件
        button_sendVerificationBtn.setOnClickListener(this);
        button_verify.setOnClickListener(this);

        final SpannableStringBuilder style = new SpannableStringBuilder();
        style.append("密码登录");
        ClickableSpan clickableSpan = new ClickableSpan() {
            @Override
            public void onClick(@NonNull View widget) {
                Intent intent = new Intent(VerificationLoginActivity.this, PasswordLoginActivity.class);
                startActivity(intent);
            }
        };
        style.setSpan(clickableSpan, 0, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        style.setSpan(new ForegroundColorSpan(Color.parseColor("#8BC34A")), 0, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        toPasswordLogin.setMovementMethod(LinkMovementMethod.getInstance());
        toPasswordLogin.setText(style);

        databaseHelper = new DatabaseHelper(VerificationLoginActivity.this);
        sqLiteDatabase = databaseHelper.getReadableDatabase();

        MobSDK.submitPolicyGrantResult(true, null);

        //注册回调监听，放到发送和验证前注册，注意这里是子线程需要传到主线程中去操作后续提示
        eh = new EventHandler() {

            @Override
            public void afterEvent(int event, int result, Object data) {
                Message msg = new Message();
                msg.arg1 = event;
                msg.arg2 = result;
                msg.obj = data;
                mHandler.sendMessage(msg);
            }

        };
        SMSSDK.registerEventHandler(eh);
        Log.d("tag","VerificationLoginActivity create");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //点击发送验证码事件
            case R.id.button_sendVerification:
                phoneNumber = editText_phone.getText().toString().trim();
                //判断手机号是否为空
                if (TextUtils.isEmpty(phoneNumber)) {
                    Toast.makeText(VerificationLoginActivity.this, "手机号不能为空", Toast.LENGTH_SHORT).show();
                }
                //判断手机号是否有效
                else if(!isPhone(phoneNumber)){
                    Toast.makeText(VerificationLoginActivity.this, "无效手机号", Toast.LENGTH_SHORT).show();
                }
                //手机号有效，发送验证码，设置60s倒计时
                else {
                    SMSSDK.getVerificationCode("+86", phoneNumber);
                    TimeCountDown timeCountDown = new TimeCountDown(60*1000,1000);
                    timeCountDown.start();
                }
                break;
            case R.id.button_verify:
                //点击登录事件
                verificationCode = editText_verification.getText().toString();
                //验证码不为空，前往验证
                if (!TextUtils.isEmpty(verificationCode)) {
                    SMSSDK.submitVerificationCode("+86", phoneNumber, verificationCode);
                }
                //验证码为空
                else {
                    Toast.makeText(VerificationLoginActivity.this, "验证码不能为空", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    @Override
    protected void onDestroy() {
        SMSSDK.unregisterEventHandler(eh);
        super.onDestroy();
    }

    private class TimeCountDown extends CountDownTimer {
        public TimeCountDown(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            button_sendVerificationBtn.setClickable(false);
            button_sendVerificationBtn.setText("重新发送（"+millisUntilFinished/1000+"s）");
        }

        @Override
        public void onFinish() {
            button_sendVerificationBtn.setText("获取验证码");
            button_sendVerificationBtn.setClickable(true);
        }
    }

    private boolean isPhone(String phone){
        String telRegex = "[1][345789]\\d{9}";//"[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
        if (TextUtils.isEmpty(phone))
            return false;
        else
            return phone.matches(telRegex);
    }

    private boolean isRegistered(String phone){
        Cursor cursor = sqLiteDatabase.query("users", null,"phone=?",new String[]{phone},null,null,null);
        int count = cursor.getCount();
        cursor.close();
        if(count!=0){
            return true;
        }
        return false;
    }

    @Override
    public void finish() {
        super.finish();
        Log.d("tag","VerificationLoginActivity finish");
    }
}